package com.rizzo.android.ui.fragment;

import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;
import com.rizzo.android.R;
import com.rizzo.android.content.RizzoContent;
import com.rizzo.android.domain.Quota;

/**
 * Created with IntelliJ IDEA.
 * User: jalie
 * Date: 12/28/12
 * Time: 12:13 PM
 * To change this template use File | Settings | File Templates.
 */
public class QuotasFragment extends RizzoFragment implements LoaderManager.LoaderCallbacks<Cursor> {

    public static final String SEARCH_TEXT_STATE = "searchText";

    private SimpleCursorAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.trash, null);
        Log.d(this.getClass().getCanonicalName(), "onCreateView");
        return inflate;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.findViewById(R.id.relative_layout).setBackground(getResources().getDrawable(R.drawable.trash1));

        String[] from = new String[]{Quota.METHOD_FIELD, Quota.USER_FIELD, Quota.HITS_FIELD};
//		int[] to = new int[]{R.id.method, R.id.user, R.id.hits};
//		this.adapter = new SimpleCursorAdapter(getActivity(), R.layout.quota_list_view_row, null, from, to, 0);
//		getLoaderManager().initLoader(0, null, this);
    }

    @Override
    public void onResume() {
        super.onResume();
        adapter.notifyDataSetChanged();
    }

    // TODO load the quotas data via LoaderCallbacks this way the LoaderCallback onLoadFinished will be triggered for every change
    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle savedInstanceState) {
        String[] projection = {Quota.ID_FIELD, Quota.METHOD_FIELD, Quota.USER_FIELD, Quota.HITS_FIELD};
        String selection = null;
        if (savedInstanceState != null) {
            String searchText = (String) savedInstanceState.get(SEARCH_TEXT_STATE);
            if (searchText != null && !"".equals(searchText)) {
                selection = Quota.METHOD_FIELD + " like '%" + searchText + "%'";
            }
        }
        return new CursorLoader(getActivity(),
                RizzoContent.Quota.CONTENT_URI.buildUpon().appendQueryParameter(
                        Quota.APPLICATION_FIELD, "todo-application").build(),
                projection, selection, null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        adapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        adapter.swapCursor(null);
    }
}
